#include "msgsocket.h"
#include "config.h"

MsgSocket::MsgSocket(QString ipAddr, int port, QObject *parent)
    : QObject(parent)
{
    m_socket = new QTcpSocket(this);

    connect(m_socket, SIGNAL(readyRead()),
            this, SLOT(slotReadyRead()));

    m_socket->connectToHost(ipAddr, port);
}

MsgSocket::~MsgSocket()
{
    if(m_socket->isOpen())
    {
       m_socket->disconnectFromHost();
    }
    delete m_socket;
}

void MsgSocket::disconnectFromHost()
{
    if(m_socket->isOpen())
    {
       m_socket->disconnectFromHost();
    }
}

void MsgSocket::slotReadyRead()
{
    QString data = QString::fromLatin1(m_socket->readAll());
    QStringList list = data.split("#");
    if(list.length() > 1)
    {
        Config::m_rateRecvTPS += data.length();
        Config::m_packetRecvNumber++;
        int msgId = list.at(0).toInt();
        if(Config::m_msgTimeMap.contains(msgId))
        {
            QTime *t = Config::m_msgTimeMap[msgId];
            Config::m_resTimeList.append(t->elapsed());
            Config::m_msgTimeMap.remove(msgId);
            delete t;
        }
        qDebug() << "Recv: " << list.at(1);
    }
}

void MsgSocket::slotSendMsg(int index, const QString &msg)
{
    qDebug() << "Send: " << msg;
    QString data = QString::number(index) + "#" + msg;
    Config::m_rateSendTPS += data.length();
    Config::m_packetSendNumber++;
    QTime *t = new QTime;
    t->start();
    Config::m_msgTimeMap.insert(index, t);
    m_socket->write(data.toLatin1());
}
